﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Delay;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;

namespace PhoneInfo.Page
{


    public partial class MobileProduct : PhoneApplicationPage
    {
        private ProgressIndicator _progress = new ProgressIndicator() { IsVisible = false, IsIndeterminate = true };
        TypeArea typeEurope_America = null;
        TypeArea typeJapen_Krean = null;
        TypeArea typeLoacl = null;
        TypeArea typeTaiwan = null;
        bool ispk = false;
        bool isnull = false;
        string pid_1;
        string ppid_1;
        string price_1;
        string picurl_1;
        string phonename_1;
        string ppname_1;

        private int lastPage = -1;
        public MobileProduct()
        {
            InitializeComponent();
            this.SetValue(SystemTray.OpacityProperty, 0.00001);
            if (App.appSitting.Theme == 1)
                ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch"];
            else
                ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch1"];
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (NavigationContext.QueryString.ContainsKey("ispk"))
            {
                ispk = true;
                if (NavigationContext.QueryString.ContainsKey("isnull"))
                {
                    isnull = true;
                }
                else
                {
                    pid_1 = NavigationContext.QueryString["pid_1"];
                    ppid_1 = NavigationContext.QueryString["ppid_1"];
                    price_1 = NavigationContext.QueryString["price_1"];
                    picurl_1 = NavigationContext.QueryString["picurl_1"];
                    phonename_1 = NavigationContext.QueryString["phonename_1"];
                    ppname_1 = NavigationContext.QueryString["ppname_1"];
                }
            }

            SystemTray.ProgressIndicator = this._progress;
            this._progress.IsVisible = false;
        }
        private void RankingTap(object sender, System.Windows.Input.GestureEventArgs e)
        {   //排行点击
            if (sender == null) return;
            ListBox ls = sender as ListBox;
            if (ls == null) return;
            string pagename = "/Page/HotPhone.xaml?classid=" + (ls.SelectedIndex + 1).ToString();
            NavigationService.Navigate(new Uri(pagename, UriKind.Relative));
        }
        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender == null) return;
            Pivot pv = sender as Pivot;
            if (pv == null) return;
            switch (pv.SelectedIndex)
            {
                case 0:
                    if (App.appSitting.Theme == 1)
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch"];
                    else
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch1"];
                    if (typeEurope_America == null)
                    {
                        typeEurope_America = new TypeArea();
                        _progress.IsVisible = true;
                        typeEurope_America.Result = 0;
                        typeEurope_America.CurrentPage = 1;
                        typeEurope_America.TotalPage = 0;
                        typeEurope_America.PageSize = 20;
                        typeEurope_America.AllowAdd = false;
                        typeEurope_America.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(typeEurope_America.GetPhoneInfoUrl("1", typeEurope_America.CurrentPage)));
                        typeEurope_America.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(type_PropertyChanged);
                        Europe_and_American.DataContext = typeEurope_America;
                    }
                    //欧美
                    break;
                case 1:
                    if (App.appSitting.Theme == 1)
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch"];
                    else
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch1"];
                    if (typeJapen_Krean == null)
                    {
                        typeJapen_Krean = new TypeArea();
                        _progress.IsVisible = true;
                        typeJapen_Krean.Result = 0;
                        typeJapen_Krean.CurrentPage = 1;
                        typeJapen_Krean.TotalPage = 0;
                        typeJapen_Krean.PageSize = 20;
                        typeJapen_Krean.AllowAdd = false;
                        typeJapen_Krean.SetValue(LowProfileXmlLoader.UriSourceProperty,
                                                 new Uri(typeJapen_Krean.GetPhoneInfoUrl("2",
                                                                         typeJapen_Krean.CurrentPage)));
                        typeJapen_Krean.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(
                                                               type_PropertyChanged);
                        Japan_and_Krean.DataContext = typeJapen_Krean;
                    }
                    //日韩
                    break;
                case 2:
                    if (App.appSitting.Theme == 1)
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch"];
                    else
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch1"];
                    if (typeLoacl == null)
                    {
                        typeLoacl = new TypeArea();
                        _progress.IsVisible = true;
                        typeLoacl.Result = 0;
                        typeLoacl.CurrentPage = 1;
                        typeLoacl.TotalPage = 0;
                        typeLoacl.PageSize = 20;
                        typeLoacl.AllowAdd = false;
                        typeLoacl.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(
                                           typeLoacl.GetPhoneInfoUrl("3", typeLoacl.CurrentPage)));
                        typeLoacl.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(type_PropertyChanged);
                        Local.DataContext = typeLoacl;
                    }
                    //国产
                    break;
                case 3:
                    if (App.appSitting.Theme == 1)
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch"];
                    else
                        ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch1"];
                    if (typeTaiwan == null)
                    {
                        typeTaiwan = new TypeArea();
                        _progress.IsVisible = true;
                        typeTaiwan.Result = 0;
                        typeTaiwan.CurrentPage = 1;
                        typeTaiwan.TotalPage = 0;
                        typeTaiwan.PageSize = 20;
                        typeTaiwan.AllowAdd = false;
                        typeTaiwan.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(
                                            typeTaiwan.GetPhoneInfoUrl("4", typeTaiwan.CurrentPage)));
                        typeTaiwan.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(type_PropertyChanged);
                        Taiwan.DataContext = typeTaiwan;
                    }
                    //台湾
                    break;
            }
        }
        void type_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (sender == null) return;
            TypeArea pv = sender as TypeArea;
            if (pv == null) return;
            else if (e.PropertyName == "Result")
            {
                _progress.IsVisible = false;
                switch (pv.Result)
                {
                    case -1:
                    //网络错误
                    case 1:
                        //失败
                        switch (mainPivot.SelectedIndex)
                        {
                            case 0:
                                break;
                            case 1:
                                EuropeAndAmerican_result.Visibility = Visibility.Visible;
                                break;
                            case 2:
                                JapenAndKrean_result.Visibility = Visibility.Visible;
                                break;
                            case 3:
                                Local_result.Visibility = Visibility.Visible;
                                break;
                            case 4:
                                Taiwan_result.Visibility = Visibility.Visible;
                                break;
                        }
                        break;
                    case 2:
                        //成功
                        break;
                }
            }
        }
        private void ListBox_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender == null) return;
            List<ScrollBar> scrollBarList = GetVisualChildCollection<ScrollBar>(sender);
            foreach (ScrollBar scrollBar in scrollBarList)
            {
                if (scrollBar.Orientation == System.Windows.Controls.Orientation.Horizontal)
                {
                }
                else
                    scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(verticalScrollBar_ValueChanged);
            }
        }
        private void verticalScrollBar_ValueChanged(object sender, RoutedEventArgs e)
        {
            ScrollBar scrollBar = (ScrollBar)sender;
            object valueObj = scrollBar.GetValue(ScrollBar.ValueProperty);
            object maxObj = scrollBar.GetValue(ScrollBar.MaximumProperty);
            if (valueObj != null && maxObj != null)
            {
                double value = (double)valueObj;
                double max = (double)maxObj - 1.5;
                Debug.WriteLine("ValueProperty si {0}", value);
                Debug.WriteLine("MaximumProperty si {0}", max);
                if (value >= max)
                {
                    if (App.appSitting.AutoLoadNextPage == false) return;
                    PivotItem currentPivot = mainPivot.SelectedItem as PivotItem;
                    if (currentPivot == null) return;
                    if (mainPivot.SelectedIndex == 0) return;
                    TypeArea ta = currentPivot.DataContext as TypeArea;
                    if (ta == null) return;
                    if (ta.CurrentPage * ta.PageSize <= ta.TotalPage)
                    {
                        if (lastPage == ta.CurrentPage) return;
                        lastPage = ta.CurrentPage;
                        ta.AllowAdd = true;
                        ta.Result = 0;
                        _progress.IsVisible = true;
                        ta.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(ta.GetPhoneInfoUrl(mainPivot.SelectedIndex.ToString(), ta.CurrentPage + 1)));
                    }
                }
            }
        }
        public static List<T> GetVisualChildCollection<T>(object parent) where T : UIElement
        {
            List<T> visualCollection = new List<T>();
            GetVisualChildCollection(parent as DependencyObject, visualCollection);
            return visualCollection;
        }
        private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : UIElement
        {
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);
                if (child is T)
                {
                    visualCollection.Add(child as T);
                }
                else if (child != null)
                {
                    GetVisualChildCollection(child, visualCollection);
                }
            }
        }
        private void ListBox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (sender == null) return;
            ListBox lb = sender as ListBox;
            if (lb == null) return;
            TypeAreaItem pkItem = lb.SelectedItem as TypeAreaItem;
            if (pkItem == null) return;
            if (pkItem.Type == "Main")
            {
                string pagename = "/Page/HotPhone.xaml";
                pagename += "?ppid=" + pkItem.Ppid;
                if (ispk)
                {
                    if (!isnull)
                    {
                        pagename += "&ispk=1&pid_1=" + pid_1;
                        pagename += "&ppid_1=" + ppid_1;
                        pagename += "&price_1=" + price_1;
                        pagename += "&picurl_1=" + picurl_1;
                        pagename += "&phonename_1=" + phonename_1;
                        pagename += "&ppname_1=" + ppname_1;
                    }
                    else
                    {
                        pagename += "&ispk=1&isnull=1";
                    }
                }
                NavigationService.Navigate(new Uri(pagename, UriKind.Relative));
            }
            else
            {//加载下一页
                if (App.appSitting.AutoLoadNextPage == false)
                {
                    PivotItem currentPivot = mainPivot.SelectedItem as PivotItem;
                    if (currentPivot == null) return;
                    if (mainPivot.SelectedIndex == 0) return;
                    TypeArea ta = currentPivot.DataContext as TypeArea;
                    if (ta == null) return;
                    if (ta.CurrentPage * ta.PageSize <= ta.TotalPage)
                    {
                        if (lastPage == ta.CurrentPage) return;
                        lastPage = ta.CurrentPage;
                        ta.AllowAdd = true;
                        ta.Result = 0;
                        _progress.IsVisible = true;
                        ta.SetValue(LowProfileXmlLoader.UriSourceProperty, new Uri(ta.GetPhoneInfoUrl(mainPivot.SelectedIndex.ToString(), ta.CurrentPage + 1)));
                    }
                }
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }
        private void mianPage(object sender, EventArgs e)
        {
            string objective = "/Page/main.xaml";
            NavigationService.Navigate(new Uri(objective, UriKind.Relative));
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            if (SerchPop.IsOpen)
            {
                SerchPop.IsOpen = false;
                if (App.appSitting.Theme == 1)
                    ApplicationBar = (ApplicationBar)this.Resources["AppBarSendSearch"];
                else
                    ApplicationBar = (ApplicationBar)this.Resources["AppBarSendSearch1"];

                e.Cancel = true;
                return;
            }
            string pageName = "/Page/main.xaml";
            NavigationService.Navigate(new Uri(pageName, UriKind.Relative));
        }
        
        private void search(object sender, EventArgs e)
        {
            if (App.appSitting.Theme == 1)
                ApplicationBar = (ApplicationBar)this.Resources["AppBarSendSearch"];
            else
                ApplicationBar = (ApplicationBar)this.Resources["AppBarSendSearch1"];
            SerchPop.IsOpen = true;
            textresult.Focus();
        }
        private void Canvas_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SerchPop.IsOpen = false;
            textresult.Focus();
            if (App.appSitting.Theme == 1)
                ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch"];
            else
                ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch1"];
        }
        private void send(object sender, EventArgs e)
        {
            string content = this.textresult.Text;
            if (content.Length <= 0)
                MessageBox.Show("搜索的关键字不能为空");
            else
            {
                string ag = "";
                if (ispk)
                    ag += "&ispk=1";
                if (isnull)
                    ag += "&isnull=1";
                ag += "&pid_1=" + pid_1;
                ag += "&ppid_1=" + ppid_1;
                ag += "&price_1=" + price_1;
                ag += "&picurl_1=" + picurl_1;
                ag += "&phonename_1=" + phonename_1;
                ag += "&ppname_1=" + ppname_1;
                string pageName = "/Page/ProfectSearch.xaml";
                pageName = pageName + "?valuekey=" + content + ag;
                base.NavigationService.Navigate(new Uri(pageName, UriKind.Relative));
                if (App.appSitting.Theme == 1)
                    base.ApplicationBar = (ApplicationBar)base.Resources["AppBarSearch"];
                else
                    base.ApplicationBar = (ApplicationBar)base.Resources["AppBarSearch1"];
            }
        }
        private void cancel(object sender, EventArgs e)
        {
            SerchPop.IsOpen = false;
            if (App.appSitting.Theme == 1)
                ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch"];
            else
                ApplicationBar = (ApplicationBar)this.Resources["AppBarSearch1"];
        }
        private void textresult_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            e.Handled = true;
        }

    }
}